<?php

class MailLog {

  private $msg_body;
  private $msg_subject;
  private $error_subject;
  private $rcpt_array = array();
  private $log_errors_only = false;
  private $error_happened = false;
  
  public function to($rcpt = null) {
    if( is_null($rcpt) ) { return $this->rcpt_array; }
    
    if(!in_array($rcpt, $this->rcpt_array)){
      $this->rcpt_array[] = $rcpt;
    }
    
    return $this;
  }
  
  public function subject($subject = null) {
    if(is_null($subject) ) { return $this->msg_subject; }
    $this->msg_subject = $subject;
    return $this;
  }
  
  public function errorSubject($subject = null) {
    if(is_null($subject) ) { return $this->error_subject; }
    $this->error_subject = $subject;
    return $this;
  }
  
  public function log($message) {
    if(!$this->log_errors_only) { $this->do_log($message); }
    return $message . "\n";
  }

  private function do_log($message) {
    $this->msg_body .= $message . "\n";
    return $message . "\n";
  }
  
  public function error($message) {
    $this->error_happened = true;
    return $this->do_log($message);
  }
  
  public function send_mail(){
    if(!empty($this->msg_body)){
      if($this->error_happened) {
        if(empty($this->error_subject)) { $this->error_subject = "Proceso con errores: " . $this->msg_subject; }
        $this->msg_subject = $this->error_subject;
      }
      mail(implode(", ",$this->rcpt_array), $this->msg_subject, $this->msg_body);
      $this->msg_body = "";
    }
    return $this;
  }
  
  public function __destruct(){
    $this->send_mail();
  }
  
}